//树数据相关操作
import { OrderRule } from "/@/api/models";
interface TreeDataItem<T> {
  children?: T[];
  [key: string]: any;
}

export function findItemByKey<T extends TreeDataItem<T>>(
  data: T[],
  keyValue: string | number,
  keyName = "id"
): T | null {
  for (let i = 0, ii = data.length; i < ii; i++) {
    const item = data[i];
    if (item[keyName] === keyValue) {
      return item;
    }
    if (item.children && item.children.length > 0) {
      const result = findItemByKey(item.children, keyValue, keyName);
      if (result) {
        return result;
      }
    }
  }
  return null;
}

export function loopItem<T extends TreeDataItem<T>>(data: T[], loop: (item: T) => boolean | void): boolean | void {
  for (let i = 0, ii = data.length; i < ii; i++) {
    const item = data[i];
    if (loop(item) === false) {
      return false;
    }
    if (item.children && item.children.length > 0) {
      const result = loopItem(item.children, loop);
      if (result === false) {
        return;
      }
    }
  }
}

export function findParents<T extends TreeDataItem<T>>(
  data: T[],
  keyValue: string | number,
  keyName = "id",
  parentKeys: any[],
  parentData?: T[]
) {
  for (let i = 0, ii = data.length; i < ii; i++) {
    const item = data[i];
    if (item[keyName] === keyValue) {
      return false;
    }
    const ch = item.children;
    if (ch && ch.length > 0) {
      parentKeys.push(item[keyName]);
      parentData?.push(item);
      if (findParents(ch, keyValue, keyName, parentKeys, parentData) === false) {
        return false;
      }
    }
  }
  parentKeys.pop();
  parentData?.pop();
}

export function sortItems<T extends TreeDataItem<T>>(data: T[], sortKey = "sortValue", sortOrder = OrderRule.ASC) {
  data.sort((a, b) => {
    const v1 = a[sortKey] || 0;
    const v2 = b[sortKey] || 0;
    return sortOrder === OrderRule.ASC ? v1 - v2 : v2 - v1;
  });
  for (let i = 0, ii = data.length; i < ii; i++) {
    const item = data[i];
    const ch = item.children;
    if (ch && ch.length > 0) {
      sortItems(ch, sortKey, sortOrder);
    }
  }
}
